<?php

/**
 * Created by hbbzy.me.
 * project: frame
 * User: hbbzy
 * Date: 2018/2/17
 * Time: 21:14
 */
namespace app\backend\controller;

use think\Db;
use app\backend\model\UserModel;

class Login extends Base
{
    public function login(){
        if((new UserModel())->checkLogin()){
            return $this->redirect('/backend/index/index');
        }
        return $this->fetch();
    }

    public function doLogin(){
        $data = $this->request->post();
        //是否禁止登录
        if(!empty(session('login_disable_time')) && session('login_disable_time') + 1800 > time()){
            $this->error('login_error_timer');
        }

        $validate = $this->validate($data,[
           // 'captcha|验证码'=>'require|captcha',
            'username'=>'require|min:5|max:32',
            'password'=>'require|min:6|max:18'
        ]);
        if($validate !== true){
            $this->error($validate);
        }
        $userModel = new UserModel();
        //记录登录日志
        Db::name("manage_log")->insert(array('username'=> $data['username'],'handle'=>'用户：'.$data['username'].'尝试登录后台','handle_desc'=>'用户：'.$data['username'].'尝试登录后台','ip'=>$this->request->ip($type = 1),'time'=>date('Y-m-d H:i:s',time())));
        $record = Db::name('manage')->where('username',$data['username'])->find();
        if(!$record){
            $this->error(lang('username_or_password_error'));
        }else if(($record['error_timer']/5 > 0 && $record['error_timer'] % 5 == 0)){//错误计数达到5的倍数时
            session('login_disable_time',time());//设置禁止登录的初始时间
            $this->error(lang('login_error_timer'));
        }else if($userModel->getPWD($data['password'],$record['halt']) !== $record['passwd']){
            //更新错误计数
            $error_timer = $record['error_timer'] + 1;
            Db::name('manage')->where('id', $record['id'])->update(array('error_timer'=>$error_timer));
            $this->error(lang('username_or_password_error'));
        }
        session('user',$record);
        //更新最后登录时间，清空登录错误计数
        Db::name('manage')->where('id', $record['id'])->update(array('last_time'=>date('Y-m-d H:i:s',time()),'error_timer'=>0));
        //清除禁止登录时间
        session('login_disable_time',null);

        $this->success(lang('login_success'), '/backend/index/index');
    }

    public function doLogout(){
        session('user',null);
        $this->success(lang('logout_success'), '/');
    }
}